import axios, { type AxiosRequestHeaders } from "axios"
import storage from "@/utils/storage"
import { reGetToken } from "@/api/refresh_token"
const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL + "/",
  timeout: 10000,
})
instance.interceptors.request.use(
  function (config: any) {
    if (!config.headers) {
      config.headers = {} as AxiosRequestHeaders
    }
    if (storage.get("token")) {
      config.headers.authorization = `Bearer ${storage.get("token")}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
instance.interceptors.response.use(
  async function (response) {
    if (response.data.msg == "验签失败") {
      const res = await reGetToken("/bem/rgettoken")
      if (res.code == 200) {
        storage.set("token", res.data.token)
        storage.set("refresh_token", res.data.refresh_token)
        return {
          code: 200,
          msg: "登录状态续签成功",
        }
      }
    }
    return response.data
  },
  function (error) {
    if (error.code == "ERR_NETWORK") {
      // router.push({ name: "login" })
      return Promise.reject({ code: 300, msg: "服务器网络异常,请刷新后重试" })
    }
    if (error.response) {
      // const { status } = error.response
    }
    return Promise.reject(error)
  }
)
const Get = (url: string, params?: any) => instance.get(url, { params })
const Post = (url: string, data?: any) => instance.post(url, data)
const Put = (url: string, params?: any, data?: any) => instance.put(url, { params }, data)
const Delete = (url: string, params?: any) => instance.delete(url, { params })

export { Get, Post, Put, Delete, instance }
